#!/bin/sh
# GPLv3
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.

DESTDIR="/usr/local"
OPTDIR="/opt"
LOCAL=0
REMOTE=0

set -e

fxremove() {
    rm "$DESTDIR"/bin/firefox
    rm "$DESTDIR"/share/applications/firefox.desktop
}
    
fxinstall() {
    wget --check-certificate=quiet -qO- "https://download.mozilla.org/?product=firefox-latest&os=linux64&lang=en-US" | tar xjv -C "$OPTDIR"

    #VERSION=`fgrep Milestone /opt/firefox/platform.ini | cut -d"=" -f1`
    ln -srf "$OPTDIR"/firefox/firefox "$DESTDIR"/bin/firefox

    if ! [ -d "$DESTDIR"/share/applications ]; then
	echo "Destination directory not found."
	echo "Creating directory..."
	echo "Is your destination directory a valid location for .desktop files?"
	mkdir -p "$DESTDIR"/share/applications
    fi
    
    if ! [ -e "$DESTDIR"/share/applications/firefox.desktop ]; then
	cat >> "$DESTDIR"/share/applications/firefox.desktop <<END
[Desktop Entry]
Name=Mozilla Firefox
GenericName=Firefox
Comment=Web browser
Categories=Internet;
Exec=firefox %U
Icon=$OPTDIR/firefox/browser/chrome/icons/default/default128.png
MimeType=text/html;text/xml;application/xhtml_xml;x-scheme-handler/http;x-scheme-handler/https;x-scheme-handler/ftp;
StartupNotify=true
Terminal=false
Type=Application
END
fi
}

# process verbose and help and dryrun options
while [ True ]; do
if [ "$1" = "--help" -o "$1" = "-h" ]; then
    echo " "
    echo "$0 [--local|--remove]"
    echo " "
    exit
elif [ "$1" = "--local" -o "$1" = "-l" -o "$1" = "--user" -o "$1" = "-u" ]; then
    DESTDIR="$HOME/.local"
    OPTDIR="$HOME/bin"
    LOCAL=1
    shift 1
elif [ "$1" = "--remove" -o "$1" = "-r" -o "$1" = "--uninstall" -o "$1" = "-u" ]; then
    DESTDIR="$HOME/.local"
    OPTDIR="$HOME/bin"
    REMOVE=1
    shift 1
else
    break
fi
done

# check to see if root
if ! [ x$LOCAL = "x1" ]; then
    if ! [ $(id -u) = 0 ]; then
	echo "You must be root to run this script."
	exit 1
    fi
fi

/usr/bin/rm -rf "$OPTDIR"/firefox || true

if [ x$REMOVE = "x1" ]; then
    fxremove
else
    fxinstall
fi

